package com.seeyon.apps.kk.manager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.kk.utils.CoreUtils;
import com.seeyon.kk.utils.ValueUtils;
import com.seeyon.v3x.services.ServiceException;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;

/**
 * 向邮箱系统推送组织架构数据
 * 
 * @author seeyon
 *
 */
public class OrgSyncEmailManagerImpl extends BaseManager {

	private static final Logger log = LoggerFactory.getLogger(OrgSyncEmailManagerImpl.class);

	/**
	 * 正则去除HTML转义符 如：&nbsp; &gt; &lt;
	 */
	private static final String regEx_special = "\\&[a-zA-Z]{1,10};";

	private FreemarkFlowManager freemarkFlowManager;

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	private Map<String, String> rsMap = new HashMap<>(); // 记录完成信息

	/**
	 * email 组织架构初始化 只调用一次
	 * 
	 * @return
	 */
	public Map<String, String> init() {
		rsMap.put("code", "1000");
		rsMap.put("message", "Email orgSync is ok!");
		if (!this.addDept())
			return rsMap;
		if (!this.addUser())
			return rsMap;
		return rsMap;
	}

	public boolean addDept() {
		log.info("================shkk email部门添加 start====================");
		String deptSync = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_DEPT_ADD_EMAILSQL.ftl",
				null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(deptSync);
			for (Map<String, Object> map : list) {
				Map<String, Object> param = Maps.newHashMap();
				param.put("passkey", CoreUtils.emailMd5());
				param.put("unitou", MapUtils.getString(map, "code"));
				param.put("name", MapUtils.getString(map, "name"));
				// 一级部门 通过ParentPath 获取不到 部门对象
				if (null == MapUtils.getString(map, "parentcode")) {
					param.put("baseou", ""); // email 一级部门 为空
				} else {
					param.put("baseou", MapUtils.getString(map, "parentcode"));
				}
				// eamil Url
				String urlParams = CoreUtils.buildUrlParamter(param);
				log.info("=========shkk email urlParams:" + urlParams);
				String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_unitadd";
				String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
			}
			log.info("================shkk email部门添加 start====================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			log.info("================shkk email部门添加错误：{}", e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
		}
		return false;
	}

	public boolean addUser() {
		log.info("================shkk email部门添加 start====================");
		String deptSync = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_MEMBER_ADD_EMAILSQL.ftl",
				null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(deptSync);
			for (Map<String, Object> map : list) {
				Map<String, Object> param = Maps.newHashMap();
				param.put("passkey", CoreUtils.emailMd5());
				param.put("mail",
						MapUtils.getString(map, "loginName") + ValueUtils.getConfig().getString("shkk.email"));
				param.put("name", MapUtils.getString(map, "userName"));
				param.put("password", "admin_12345");
				param.put("host", ValueUtils.getConfig().getString("shkk.emailHost"));
				param.put("role", "2");
				param.put("unitou", MapUtils.getString(map, "ou"));
				// email 用户扩展属性
				Map<String, Object> exarrt = Maps.newHashMap();
				exarrt.put("extauthid", MapUtils.getString(map, "code"));
				exarrt.put("status", 1);
				exarrt.put("mj", MapUtils.getString(map, "secretLevel"));
				param.put("extattr", exarrt.toString().replace("{", "").replace("}", "").replace(" ", ""));
				// eamil Url
				String urlParams = CoreUtils.buildUrlParamter(param);
				String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_adduser";
				String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
			}
			log.info("================shkk email 添加人员 start====================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			log.info("================shkk email添加人员错误：{}", e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
		}
		return false;
	}

	/**
	 * 未读邮件消息提醒
	 * 
	 * @param loginName
	 */
	public void sendMsg(String loginName) {
		try {
			Map<String, Object> param = Maps.newHashMap();
			param.put("user", loginName + ValueUtils.getConfig().getString("shkk.email"));
			param.put("passkey", CoreUtils.emailMd5());
			param.put("count", "100");
			param.put("onlynew", "yes");
			String urlParams = CoreUtils.buildUrlParamter(param);
			log.info("=========shkk email get massage urlParams:{}", urlParams);
			String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "newuser.php/g7_listinboxmail";
			String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
			log.info("=======shkk email result:{}", result);
			Map<String, Object> rsMap = JSON.parseObject(result);
			if (MapUtils.getInteger(rsMap, "errcode") == 0) {
				JSONArray list = JSONArray.parseArray(MapUtils.getString(rsMap, "result"));
				for (Object object : list) {
					Map<String, Object> temp = JSON.parseObject(object.toString().replaceAll(regEx_special, ""));
					String[] from = MapUtils.getString(temp, "from").split(" ");
					String sendLoginName = "";
					if (from[1].indexOf("@") != -1) {
						sendLoginName = from[1].substring(0, from[1].indexOf("@"));
					}
					String sql = "SELECT ID FROM FORMMAIN_2996 WHERE FIELD0003 = '" + MapUtils.getString(temp, "id")
							+ "'";
					List<Map<String, Object>> tempList = this.jdbcTemplate.queryForList(sql);
					if (tempList.isEmpty()) {
						String dataXML = this.freemarkFlowManager
								.fltTemplateIntoString("datasync/emailandlog/addEmailMsgXML.ftl", temp);
						// 可以使用数据模板生成，这样底表事件依然有效
						FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
						FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
						for (FormExport formExport : formExports) {
							formFactory.importBusinessFormData("oa2", "SH_EMAIL_0001", formExport, null);
						}
						log.info("==========shkk get email massage is ok !");
						// 调用OA接口 推送消息
						String token = CoreUtils.doGet(ValueUtils.getConfig().getString("shkk.getOAsystemToken"), null,
								"utf-8", false);
						if (token.startsWith("{")) {
							JSONObject tokenJson = JSONObject.parseObject(token);
							token = tokenJson.getString("id");
						}
						Map<String, Object> params = Maps.newHashMap();
						params.put("token", token);
						params.put("senderLoginName", sendLoginName);
						List<Object> loginNames = Lists.newArrayList();
						loginNames.add(loginName);
						params.put("loginNames", loginNames);
						SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String content = "(新邮件 " + sp.format(MapUtils.getLongValue(temp, "time") * 1000) + ")";
						params.put("content", content + MapUtils.getString(temp, "subject"));
						params.put("url", Lists.newArrayList());
						String rsMsg = CoreUtils.doPost(ValueUtils.getConfig().getString("shkk.getOAMassage"), params,
								JSON.toJSONString(params), "UTF-8", true);
						log.info("==============shkk email message to oa is ok !:{}", rsMsg);
					}
				}
			}
		} catch (Exception e) {
			log.info("=========shkk get email massage error:{}", e.getMessage());
		}
	}
}
